home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 6845 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: news.compuserve.com!newsmaster
  2. From: 71247.3221@compuserve.com (Don Wallace)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: C++ gurus, I have a question for you!
  5. Date: Tue, 20 Feb 1996 07:17:08 GMT
  6. Organization: CompuServe Incorporated
  7. Message-ID: <4gbi49$38m@dub-news-svc-1.compuserve.com>
  8. References: <31281804.687F@iglou.com>
  9. NNTP-Posting-Host: hd48-175.compuserve.com
  10. X-Newsreader: Forte Free Agent v0.55
  11.  
  12. "Abe L. Getchell" <panther@iglou.com> wrote:
  13.  
  14. >How is it possible to check if a variable has been
  15. >initialized yet?  If I do 'if ( !a ) { int a = 1 }' I get
  16. >an error message.  Please, any help would be great.  Reply
  17. >to the group or in mail.  Thanks in advance!
  18.  
  19. >Abe L. Getchell
  20.  
  21. Abe,
  22.  
  23. There are two kinds of variable storage in C++: global or
  24. extern-class, which are variables declared outside a function; and
  25. automatic ('local') variables, those declared inside a function, whose
  26. lifetime is one call of a function.
  27.  
  28. A global/extern variable is always initialized to binary 0's when a
  29. program starts. Its lifetime is the life of the program. 
  30.  
  31. An automatic variable is not initialized to anything when its function
  32. is run. It will contain random garbage if it is not set to anything
  33. explicitly.
  34.  
  35. But I also see a major problem with your understanding of variable
  36. scope in the code you supply:
  37.  
  38. if ( !a ) 
  39.     int a = 1;
  40. }
  41.  
  42. The code above is declaring a new variable also named 'a' whose scope
  43. is within the braces. This new 'a' inside the brackets is completely
  44. different than the 'a' you are testing in the if(!a).
  45.  
  46. Just initialize your global or auto variables to a known value before
  47. trying to test or use them. And picking up a beginning book on 'C'
  48. wouldn't hurt either...
  49.  
  50. - Don
  51.  
  52.